﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml;

using Word = Microsoft.Office.Interop.Word;

namespace SafetyRecord
{
    public partial class SafetyForm : Form
    {
        /**
         * 设置一个值确定当前是什么类型的文书，默认为 0
         * 当值为 0 表示文书一般类型
         * 当值为 1 表示文书是事故调查类型
         * */
        private int TEMPLATE_TYPE = 0;

        private string TITLE = string.Empty;

        private SoundRecord m_Record = new SoundRecord();

        /**
         * 当前Tab选中的索引
         * */
        private int currentIndex = 0;

        /**
         * word对象
         * */
        private Word.Application app;        

        public SafetyForm()
        {
            InitializeComponent();
        }

        private void SafetyForm_Load(object sender, EventArgs e)
        {
            this.tabControl.SizeMode = TabSizeMode.Fixed;
            this.tabControl.ItemSize = new Size(0, 1);
            this.btnLast.Enabled = false;
            this.btnRemove.Enabled = false;

            InitFormControlsValues();

            ComboBoxDataBinding();

            TITLE = "诸暨市生产安全行政执法文书";
        }

        /// <summary>
        /// 首次运行初始化问答列表控件
        /// </summary>
        private void InitRecordControl(object sender, EventArgs e)
        {
            List<Dictionary<string, List<string>>> wentiList = new List<Dictionary<string, List<string>>>();
            List<Dictionary<string, List<string>>> daanList = new List<Dictionary<string, List<string>>>();
            wentiList.Add(new Dictionary<string,List<string>>());
            daanList.Add(new Dictionary<string, List<string>>());
            wentiList[0]["wenti1"] = new List<string>();
            wentiList[0]["wenti1"].Add(IntroduceTextBox.Text.Trim());
            daanList[0]["daan1"] = new List<string>();
            daanList[0]["daan1"].Add("听清楚了。");
            wentiList[0]["wenti2"] = new List<string>();
            wentiList[0]["wenti2"].Add("你叫什么名字，在何单位工作，任何职务？");
            daanList[0]["daan2"] = new List<string>();
            daanList[0]["daan2"].Add(BeAskerTextBox.Text.Trim());
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("r04.xml");
            XmlNode xmlRoot = xmlDoc.SelectSingleNode("XmlDS");
            if (xmlRoot.HasChildNodes)
            {
                int Index = 0;
                int Order = 0;
                int OrderIndex =0;
                foreach (XmlNode wdNode in xmlRoot.ChildNodes)
                {
                    XmlElement wdEle = (XmlElement)wdNode;
                    Order = int.Parse(wdEle.Attributes["Order"].Value);
                    OrderIndex = Order% 14;
                    OrderIndex = OrderIndex == 0 ? 14 :OrderIndex;
                    if(OrderIndex == 1){
                        ++Index;
                        wentiList.Add(new Dictionary<string,List<string>>());
                        daanList.Add(new Dictionary<string,List<string>>());
                    }

                    if (wdEle.HasChildNodes)
                    {
                        foreach (XmlNode contentNode in wdEle.ChildNodes)
                        {
                            if (contentNode.Name == "wenti")
                            {
                                List<string> wenList = null;
                                if (wentiList[Index].ContainsKey("wenti" + OrderIndex))
                                {
                                    wenList = wentiList[Index]["wenti" + OrderIndex];
                                }
                                else
                                {
                                    wenList = new List<string>();
                                }
                                wenList.Add(contentNode.InnerText);
                                wentiList[Index]["wenti" + OrderIndex] = wenList;
                            }
                            else if (contentNode.Name == "daan")
                            {
                                List<string> daList = null;
                                if (daanList[Index].ContainsKey("daan" + OrderIndex))
                                {
                                    daList = daanList[Index]["daan" + OrderIndex];
                                }
                                else
                                {
                                    daList = new List<string>();
                                }
                                daList.Add(contentNode.InnerText);
                                daanList[Index]["daan" + OrderIndex] = daList;
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < wentiList.Count; i++)
            {
                if (i > 0)
                    this.btnNext_Click(sender, e);
                Control c = tabControl.TabPages[i+1];
                if (c is TabPage)
                {
                    RecordControl rc = c.Controls[0] as RecordControl;
                    rc.InitComboBoxValue(wentiList[i], daanList[i]);
                }
            }
            this.currentIndex = 1;
            this.tabControl.SelectedIndex = this.currentIndex;
        }

        /// <summary>
        /// 首次运行或点击菜单中的新建，初始化表单内的控件。
        /// </summary>
        private void InitFormControlsValues()
        {
            // 界面空间初始值的设定
            if (GenderComboBox.Items.Count > 0)
            {
                GenderComboBox.SelectedIndex = 0;
            }
            if (IsCommunistComboBox.Items.Count > 0)
            {
                IsCommunistComboBox.SelectedIndex = 1;
            }

            if (IsNPCComboBox.Items.Count > 0)
            {
                IsNPCComboBox.SelectedIndex = 1;
            }

            // 设置 TabControl 的默认文字属性
            //tabControl.TabPages[0].Text = "询问笔录";

            // 设置日期部分控件的值。
            DateTimeFormate();
        }

        private void EmptyFormControlsValues(Panel control)
        {
            // 对象为 null 不做任何处理。
            if (control == null) return;

            foreach (Control ctl in control.Controls)
            {
                switch (ctl.GetType().Name)
                { 
                    case "TextBox":
                        ctl.Text = "";
                        break;
                    case "ComboBox":
                        ((ComboBox)ctl).SelectedIndex = -1;
                        ((ComboBox)ctl).Text = "";
                        break;
                }
            }
        }

        private void DateTimeFormate() 
        {
            // 获取当前时间
            DateTime timeNow = DateTime.Now;

            YearTextBox.Text = timeNow.Year.ToString();
            MonthTextBox.Text = timeNow.Month.ToString();
            DayTextBox.Text = Day2TextBox.Text = timeNow.Day.ToString();
            HourTextBox.Text = timeNow.Hour.ToString();
            MinuteTextBox.Text = timeNow.Minute.ToString();
            
        }

        private void AutoTimeRunner()
        {
            Day2TextBox.Text = DateTime.Now.Day.ToString();
            Hour2TextBox.Text = DateTime.Now.Hour.ToString();
            Minute2TextBox.Text = DateTime.Now.Minute.ToString();
        }

        /// <summary>    
        /// 创建节点    
        /// </summary>    
        /// <param name="xmldoc"></param>  xml文档  
        /// <param name="parentnode"></param>父节点    
        /// <param name="name"></param>  节点名  
        /// <param name="value"></param>  节点值  
        ///   
        public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
        {
            XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
            node.InnerText = value;
            parentNode.AppendChild(node);
        }  

        /// <summary>
        /// 保存xml文件
        /// </summary>
        private bool SaveXml(string xmlFile)
        {
            XmlDocument xmlDoc = new XmlDocument();
            //创建类型声明节点  
            XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xmlDoc.AppendChild(node);
            //创建根节点  
            XmlNode root = xmlDoc.CreateElement("Set");
            xmlDoc.AppendChild(root);
            CreateNode(xmlDoc, root, "title", TITLE);
            CreateNode(xmlDoc, root, "introduce", IntroduceTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "year", YearTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "month", MonthTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "day", DayTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "hour", HourTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "minute", MinuteTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "day2", Day2TextBox.Text.Trim());
            CreateNode(xmlDoc, root, "hour2", Hour2TextBox.Text.Trim());
            CreateNode(xmlDoc, root, "minute2", Minute2TextBox.Text.Trim());
            CreateNode(xmlDoc, root, "count", CountTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "askAddr", AskAddrComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "asker", AskerComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "askerOrgAndJob", AskerOrgAndJobComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "recorder", RecorderComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "recorderOrgAndJob", RecorderOrgAndJobComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "beAsker", BeAskerTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "gender", GenderComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "age", AgeTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "idNumber", IDNumberTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "phoneNumber", PhoneNumberTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "isCommunist", IsCommunistComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "isNPC", IsNPCComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "beAskerOrg", BeAskerOrgTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "beAskerJob", BeAskerJobComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "nowAddr", NowAddrTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "homeAddr", HomeAddrTextBox.Text.Trim());
            CreateNode(xmlDoc, root, "orgName", OrgNameComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "officer1", Officer1ComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "id1", Id1ComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "officer2", Officer2ComboBox.Text.Trim());
            CreateNode(xmlDoc, root, "id2", Id2ComboBox.Text.Trim());

            XmlNode wenda = xmlDoc.CreateElement("WenDa");
            root.AppendChild(wenda);
            if (this.tabControl.Controls.Count > 1)
            {
                for (int i = 1; i < tabControl.TabPages.Count;i++ )
                {
                    Control c = tabControl.TabPages[i];
                    if (c is TabPage)
                    {
                        RecordControl rc = c.Controls[0] as RecordControl;
                        Dictionary<string, Dictionary<int, string>> dict = rc.GetComboBoxs();
                        Dictionary<int, string> wenti = dict["wenti"];
                        Dictionary<int, string> daan = dict["daan"];
                        foreach (KeyValuePair<int, string> kv in wenti)
                        {
                            if (!string.IsNullOrEmpty(kv.Value))
                            {
                                CreateNode(xmlDoc, wenda, "wenti" + kv.Key + "_" + c.TabIndex, kv.Value);
                                CreateNode(xmlDoc, wenda, "daan" + kv.Key + "_" + c.TabIndex, daan[kv.Key]);
                            }
                        }
                    }
                }
            }
            try
            {
                xmlDoc.Save(xmlFile);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                //显示错误信息  
                return false;
            }

            return true;
        }

        /// <summary>
        /// 保存wrod文件
        /// </summary>
        private void SaveDoc(string filePath,string fileName,string docPath)
        {
            if (SaveXml(filePath+"\\"+fileName + ".xml"))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath + "\\" + fileName + ".xml");
                XmlNode root = xmlDoc.SelectSingleNode("Set");
                if (root.HasChildNodes)
                {
                    //Type type = Type.GetTypeFromProgID("WPS.Application");//V8
                    //if (type == null)
                    //{
                    //    type = Type.GetTypeFromProgID("KWPS.Application");//V9
                    //    if (type == null)
                    //    {
                    //        type = Type.GetTypeFromProgID("Word.Application");// MS Word 
                    //        if (type == null)
                    //        {
                    //            System.Windows.Forms.MessageBox.Show("您的计算机没有支持导出Word文档的程序", "没有找到程序");
                    //            return;
                    //        }
                    //    }
                    //}
                    try
                    {
                        app = new Word.Application();
                        FillDoc(filePath, fileName, docPath, root.ChildNodes);
                    }
                    catch
                    {
                        MessageBox.Show("请安装微软 Office 软件 2007或以上版本。","提示");
                    }
                    //app = (Microsoft.Office.Interop.Word.Application)Activator.CreateInstance(type);
                    
                }
            }
        }

        private void FillDoc(string filePath, string fileName,string docPath, XmlNodeList nodeList)
        {
            string path = Application.StartupPath + "\\template.doc";
            try
            {
                System.IO.File.Copy(path, docPath, true);
            }
            catch
            {
                MessageBox.Show("提示内容", "当前文件被锁定，请先关闭文件。", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //打开模板文件
            object oMissing = System.Reflection.Missing.Value;
            Word.Document doc = app.Documents.Open(docPath, false, false, false, "", "", false, ""
                                                            , "", 0, 0, true, false, 0, false);

            if (doc == null) return;
            //object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
            foreach (XmlNode nd in nodeList)
            {
                XmlElement element = (XmlElement)nd;
                if (element.Name == "WenDa" && element.HasChildNodes)
                {
                    if (doc.Bookmarks.Exists("WenDa"))
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (XmlNode wd in element.ChildNodes)
                        {
                            sb.AppendLine(wd.InnerText.Trim());
                        }
                        doc.Bookmarks["WenDa"].Range.Text = sb.ToString();
                    }
                }
                else
                {
                    //app.Selection.Find.Replacement.ClearFormatting();
                    //app.Selection.Find.ClearFormatting();

                    this.FindAndReplace(app, "{" + element.Name + "}", element.InnerText.Trim());
                    ////需要被替换的文本
                    //app.Selection.Find.Text = "{" + element.Name + "}";
                    ////替换文本 
                    //app.Selection.Find.Replacement.Text = text;
                    ////执行替换操作
                    //app.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    //ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    //ref replace, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                }
            }
            doc.Save();
            if (app != null)
            {
                app.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                app = null;
                MessageBox.Show("成功导出文件", "提示内容", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            this.currentIndex++;
            this.btnLast.Enabled = true;
            this.btnRemove.Enabled = true;
            if (this.tabControl.Controls.Count > this.currentIndex)
            {
                this.tabControl.SelectedIndex = this.currentIndex;
            }
            else
            {
                TabPage Page = new TabPage();
                RecordControl control = new RecordControl(this.currentIndex);
                Page.TabIndex = currentIndex;
                Page.Controls.Add(control);
                control.Dock = DockStyle.Fill;
                control.Location = new Point((Page.Width - control.Width) / 2, (Page.Height - control.Height) / 2);
                this.tabControl.Controls.Add(Page);
                this.tabControl.SelectedTab = Page;
            }
            if (this.currentIndex == 1)
                InitRecordControl(sender, e);
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            this.currentIndex--;
            if (this.currentIndex <= 0)
            {
                this.currentIndex = 0;
                this.btnLast.Enabled = false;
                this.btnRemove.Enabled = false;
            }
            this.tabControl.SelectedIndex = this.currentIndex;
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (this.currentIndex > 0)
            {
                this.tabControl.Controls.RemoveAt(this.currentIndex);
                this.btnLast_Click(sender, e);
            }
            this.btnRemove.Enabled = this.btnLast.Enabled;
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            AutoTimeRunner();
            if (this.Size.Width <= 750)
            {
                NoticeLabel.Text = DateTime.Now.ToString("h:m:s");
            }
            else
            {
                NoticeLabel.Text = DateTime.Now.ToString("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒");
            }
        }

        // 菜单的点击事件组合

        private void NewFile1()
        {
            EmptyFormControlsValues(leftPanel);

            InitFormControlsValues();

            Officer1ComboBox.Enabled = Officer2ComboBox.Enabled =
                Id1ComboBox.Enabled = Id2ComboBox.Enabled = true;

            AskReasonTextBox.Text = "就xx的有关问题";
            TITLE = "诸暨市生产安全行政执法文书";

            var num = this.tabControl.Controls.Count;
            if (num > 1)
            {
                for (int i = 1; i <= num - 1; i++)
                {
                    this.tabControl.Controls.RemoveAt(i);
                    this.currentIndex--;
                }

                if (this.currentIndex <= 0)
                {
                    this.currentIndex = 0;
                    this.btnLast.Enabled = false;
                    this.btnRemove.Enabled = false;
                }
                this.tabControl.SelectedIndex = this.currentIndex;

            }
        }

        private void NewFile2()
        {
            NewFile1();
            Officer1ComboBox.Enabled = Officer2ComboBox.Enabled =
                Id1ComboBox.Enabled = Id2ComboBox.Enabled = false;

            AskReasonTextBox.Text = "就xx的有关问题";
            TITLE = "诸暨市生产安全事故调查";

            var num = this.tabControl.Controls.Count;
            if (num > 1)
            {
                for (int i = 1; i <= num - 1; i++)
                {
                    this.tabControl.Controls.RemoveAt(i);
                    this.currentIndex--;
                }

                if (this.currentIndex <= 0)
                {
                    this.currentIndex = 0;
                    this.btnLast.Enabled = false;
                    this.btnRemove.Enabled = false;
                }
                this.tabControl.SelectedIndex = this.currentIndex;

            }

        }

        private void newFileTempAMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            NewFile1();
            TEMPLATE_TYPE = 0;
        }

        private void newFileTempBMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            NewFile2();
            TEMPLATE_TYPE = 1;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string localFilePath = String.Empty;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            string namePrefix = DateTime.Now.ToString("yyyyMMdd") + "-" + this.BeAskerOrgTextBox.Text.Trim() + "-" + this.AskerComboBox.Text.Trim();

            //设置文件类型  
            saveFileDialog1.Filter = "Word文件|*.doc;*.docx|所有文件(*.*)|*.*";
            //设置文件名称：
            saveFileDialog1.FileName = namePrefix + ".doc";

            //设置默认文件类型显示顺序  
            saveFileDialog1.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录  
            saveFileDialog1.RestoreDirectory = true;

            //点了保存按钮进入  
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //获得文件路径  
                localFilePath = saveFileDialog1.FileName.ToString();
                //获取文件路径，不带文件名  
                string FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
                SaveDoc(FilePath, namePrefix, localFilePath);
            }
        }

        private void SafetyForm_SizeChanged(object sender, EventArgs e)
        {
            // 使用 timer 控件替代。
        }

        private void OptionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Options opt = new Options();

            opt.ShowDialog();
        }

        /// <summary>
        /// 绑定数据到界面上的ComboBox控件
        /// </summary>
        private void ComboBoxDataBinding()
        {
            DataSet dataSet;
            DataTable data;
            dataSet = new DataSet();
            if (System.IO.File.Exists("r01.xml"))
            {
                
                dataSet.ReadXml("r01.xml");
                data = dataSet.Tables[0];
                foreach (DataRow row in data.Rows)
                {
                    OrgNameComboBox.Items.Add(row["org"]);
                }


                dataSet.Reset();
                data.Reset();
            }
            if (System.IO.File.Exists("r02.xml"))
            {
                dataSet.ReadXml("r02.xml");
                data = dataSet.Tables[0];
                var str = string.Empty;
                foreach (DataRow row in data.Rows)
                {
                    str = row["姓名"].ToString();
                    Officer2ComboBox.Items.Add(str);
                    Officer1ComboBox.Items.Add(str);
                    AskerComboBox.Items.Add(str);
                    RecorderComboBox.Items.Add(str);
                    str = row["执法证号"].ToString();
                    Id1ComboBox.Items.Add(str);
                    Id2ComboBox.Items.Add(str);
                    str = string.Format("{0} {1}", row["工作单位"], row["职务"]);
                    AskerOrgAndJobComboBox.Items.Add(str);
                    RecorderOrgAndJobComboBox.Items.Add(str);
                }

                dataSet.Reset();
                data.Reset();
            }

            if (System.IO.File.Exists("r03.xml"))
            {
                dataSet.ReadXml("r03.xml");
                data = dataSet.Tables[0];
                foreach (DataRow row in data.Rows)
                {
                    AskAddrComboBox.Items.Add(row["addr"]);
                }
            }
        }

        private void ControlTextChanged(object sender, EventArgs e)
        {
            string intro1 = "我们是{0}执法人员{1}、{2}，证件号码{3}、{4}，这是我们的证件（出示证件）。现依法{5}向您了解情况，您有如实回答问题的义务，提供虚假情况、作伪证是要付法律责任的，您听清楚了吗？";
            string intro2 = "我们是{0}人员，现依法{1}向您了解情况，您有如实回答问题的义务，提供虚假情况、作伪证是要付法律责任的，您听清楚了吗？";

            if (TEMPLATE_TYPE == 0)
            {
                IntroduceTextBox.Text = string.Format(intro1, OrgNameComboBox.Text, Officer1ComboBox.Text, Officer2ComboBox.Text,
                    Id1ComboBox.Text, Id2ComboBox.Text, AskReasonTextBox.Text);
            }
            else if (TEMPLATE_TYPE == 1)
            {
                IntroduceTextBox.Text = string.Format(intro2, OrgNameComboBox.Text, AskReasonTextBox.Text);
            }
        }

        private void FindAndReplace(Microsoft.Office.Interop.Word.Application doc, object findText, object replaceWithText)
        {
            object matchCase = false;
            object matchWholeWord = true;
            object matchWildCards = false;
            object matchSoundsLike = false;
            object matchAllWordForms = false;
            object forward = true;
            object format = false;
            object matchKashida = false;
            object matchDiacritics = false;
            object matchAlefHamza = false;
            object matchControl = false;
            object read_only = false;
            object visible = true;
            object replace = 2;
            object wrap = 1;
            //execute find and replace

            doc.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
                ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
                ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
        }

        private void openMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "笔录模板文件(*.xml)|*.xml";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fileDialog.FileName);
                XmlNode root = xmlDoc.SelectSingleNode("Set");
                if (root == null)
                {
                    MessageBox.Show("无法识别该文件。", "提示");
                    return;
                }
                if (root.HasChildNodes)
                {
                    try
                    {
                        foreach (XmlNode nd in root.ChildNodes)
                        {
                            XmlElement element = (XmlElement)nd;
                            if (element.Name == "WenDa" && element.HasChildNodes)
                            {
                                Dictionary<int, Dictionary<string, string>> dict = new Dictionary<int, Dictionary<string, string>>();
                                string[] names = null;
                                int index = 0;
                                string name = string.Empty;
                                foreach (XmlNode wd in element.ChildNodes)
                                {
                                    names = wd.Name.Split('_');
                                    index = int.Parse(names[1]);
                                    name = names[0];
                                    if (!dict.ContainsKey(index))
                                    {
                                        dict.Add(index, new Dictionary<string, string>());
                                    }
                                    dict[index].Add(name, wd.InnerText.Trim());
                                }


                                foreach (KeyValuePair<int, Dictionary<string, string>> kv in dict)
                                {
                                    this.btnNext_Click(sender, e);
                                }

                                if (this.tabControl.Controls.Count > 1)
                                {
                                    for (int i = 1; i < tabControl.TabPages.Count; i++)
                                    {
                                        Control c = tabControl.TabPages[i];
                                        if (c is TabPage)
                                        {
                                            RecordControl rc = c.Controls[0] as RecordControl;
                                            rc.SetComboBoxValues(dict[c.TabIndex]);
                                        }
                                    }
                                    this.currentIndex = 0;
                                    this.tabControl.SelectedIndex = this.currentIndex;
                                }
                            }
                            else
                            {
                                if (element.Name == "title")
                                    TITLE = element.InnerText.Trim();
                                else if (element.Name == "introduce")
                                    IntroduceTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "year")
                                    YearTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "month")
                                    MonthTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "day")
                                    DayTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "hour")
                                    HourTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "minute")
                                    MinuteTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "day2")
                                    Day2TextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "hour2")
                                    Hour2TextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "minute2")
                                    Minute2TextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "count")
                                    CountTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "askAddr")
                                    AskAddrComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "asker")
                                    AskerComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "askerOrgAndJob")
                                    AskerOrgAndJobComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "recorder")
                                    RecorderComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "recorderOrgAndJob")
                                    RecorderOrgAndJobComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "beAsker")
                                    BeAskerTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "gender")
                                    GenderComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "age")
                                    AgeTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "idNumber")
                                    IDNumberTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "phoneNumber")
                                    PhoneNumberTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "isCommunist")
                                    IsCommunistComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "isNPC")
                                    IsNPCComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "beAskerOrg")
                                    BeAskerOrgTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "beAskerJob")
                                    BeAskerJobComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "nowAddr")
                                    NowAddrTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "homeAddr")
                                    HomeAddrTextBox.Text = element.InnerText.Trim();
                                else if (element.Name == "orgName")
                                    OrgNameComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "officer1")
                                    Officer1ComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "id1")
                                    Id1ComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "officer2")
                                    Officer2ComboBox.Text = element.InnerText.Trim();
                                else if (element.Name == "id2")
                                    Id2ComboBox.Text = element.InnerText.Trim();
                            }
                        }
                    }
                    catch
                    {
                        MessageBox.Show("发生未知错误，可能文件被损坏。", "提示");
                    }
                }
            }
        }

        private void saveMenuItem_Click(object sender, EventArgs e)
        {
            this.btnSave_Click(sender, e);
        }

        private void openRecordMenuItemMenuItem_Click(object sender, EventArgs e)
        {
            this.m_Record.OpenRecord(); // 打开录音
            this.m_Record.StartRecord(); // 开始录音
            this.openRecordMenuItemMenuItem.Enabled = false;
            this.closeRecordMenuItemMenuItem.Enabled = true;
        }

        private void closeRecordMenuItemMenuItem_Click(object sender, EventArgs e)
        {
            this.m_Record.StopRecord(); // 停止录音
            this.m_Record.SaveRecord(@"d:\1.wav"); // 保存录音
            this.m_Record.CloseRecord(); // 关闭录音
            this.openRecordMenuItemMenuItem.Enabled = true;
            this.closeRecordMenuItemMenuItem.Enabled = false;
        }
    }
}
